import { DB } from "@/lib/db";
import { db } from "../seed";
import { exec } from "child_process";
import * as fs from "fs";
import { getStoreId, Supermarket } from "../importProducts";
import { branches, BranchSchema } from "@supersavely/db/schema";

function writeJsonToFile(filePath: string, data: any) {
  fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
}

function loadJsonFromFile(filePath: string) {
  return JSON.parse(fs.readFileSync(filePath, "utf8"));
}

function callCurl(name: string, url: string, pageToken?: string): Promise<any> {
  return new Promise((resolve, reject) => {
    const commandStart = `curl -s -X POST -d '{
          "textQuery" : "${name}",
          "pageSize": 20,
          "includedType": "supermarket",
          "locationBias": {
            "rectangle": {
              "low": {
                "latitude": -32.5514545,
                "longitude": 115.6401917
              },
              "high": {
                "latitude": -31.6355753,
                "longitude": 116.1389662
              }
            }
          },
        }' \
        -H 'Content-Type: application/json' -H 'X-Goog-Api-Key: AIzaSyByboWyTbphDOrHeiRM83-bgyneZg0wthE' \
        -H 'X-Goog-FieldMask: places.id,places.displayName,places.internationalPhoneNumber,places.nationalPhoneNumber,places.formattedAddress,places.regularOpeningHours,places.location,places.viewport,places.googleMapsUri,nextPageToken' \
        '${url}'`;

    const commandContinue = `curl -s -X POST -d '{
          "textQuery" : "${name}",
          "pageSize": 20,
          "pageToken": "${pageToken}",
          "includedType": "supermarket",
          "locationBias": {
            "rectangle": {
              "low": {
                "latitude": -32.5514545,
                "longitude": 115.6401917
              },
              "high": {
                "latitude": -31.6355753,
                "longitude": 116.1389662
              }
            }
          },
        }' \
        -H 'Content-Type: application/json' -H 'X-Goog-Api-Key: AIzaSyByboWyTbphDOrHeiRM83-bgyneZg0wthE' \
        -H 'X-Goog-FieldMask: places.id,places.displayName,places.internationalPhoneNumber,places.nationalPhoneNumber,places.formattedAddress,places.regularOpeningHours,places.location,places.viewport,places.googleMapsUri,nextPageToken' \
        ${url}`;
    const finalCommand = pageToken ? commandContinue : commandStart;
    exec(finalCommand, (error, stdout, stderr) => {
      if (error) {
        reject(`Error executing curl: ${error.message}`);
        return;
      }
      if (stderr) {
        reject(`Curl error: ${stderr}`);
        return;
      }
      try {
        const parsedResponse = JSON.parse(stdout);
        resolve(parsedResponse);
      } catch (parseError) {
        reject(`Error parsing response: ${parseError.message}`);
      }
    });
  });
}

const url = "https://places.googleapis.com/v1/places:searchText";

async function queryBranches(market: string) {
  let jsonArr: any[] = [];
  try {
    let response = await callCurl(market, url);
    const newItems = response.places;
    newItems.forEach((item) => {
      console.log("Query: ", item.displayName.text);
      jsonArr.push(item);
    });

    while (response.nextPageToken) {
      console.log("Fetching next page...");
      response = await callCurl(market, url, response.nextPageToken);
      const newItems = response.places;
      newItems.forEach((item) => {
        console.log("Query: ", item.displayName.text);
        jsonArr.push(item);
      });
    }
  } catch (error) {
    console.error("Error:", error);
  }
  return jsonArr;
}

async function importBranches(db: DB, supermarket: Supermarket, branchDatas: any) {
  const storeId = await getStoreId(supermarket);
  for (const branch of branchDatas) {
    const name = branch.displayName.text
    try {
      const branchData: Omit<
        Extract<BranchSchema, { mode: "addBranch" }>,
        "mode"
      > = {
        name: name,
        storeId: storeId,
        contactNo: branch.nationalPhoneNumber,
        address: branch.formattedAddress,
        timetable: branch.regularOpeningHours.weekdayDescriptions,
        location: {x: branch.location.longitude, y: branch.location.latitude},
        metadata: branch,
      };
      await db.insert(branches).values(branchData);
      console.log(`Inserted branch: ${name}`);
    } catch (error) {
      console.error(
        `Error inserting branch ${name}:`,
        error
      );
    }
  }
}

export async function seed(db: DB) {
  console.log("start seeding branches");
  // let jsonArr = await queryBranches("Woolworths");
  // writeJsonToFile(`Woolworths.json`, jsonArr);
  // jsonArr = await queryBranches("Coles");
  // writeJsonToFile(`Coles.json`, jsonArr);
  // let branchDatas = loadJsonFromFile("Woolworths.json");
  // await importBranches(db, Supermarket.WWS, branchDatas);
  // branchDatas = loadJsonFromFile('Coles.json');
  // await importBranches(db, Supermarket.Coles, branchDatas);
}
